package servlet.user;

import util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/register.do")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.now();
        String now = dateTime.format(formatter);
        DbUtil dbu = new DbUtil();
        String sql = "insert into user(user_name,user_psw,sex,phone,address,createTime) values ('"+username+"','"+password+"','"+sex+"','"+phone+"','"+address+"','"+now+"')";
        System.out.println(sql);
        dbu.executeUpdate(sql);
        String sql1 = "select user_id from user order by user_id desc limit 1";
        System.out.println(sql1);
        ResultSet rs= dbu.executeQuery(sql1);
        try {
            while (rs.next()){
                String userid = rs.getString(1);
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().print("<script language='javascript'>  \n" +
                        "    alert('注册成功，您的账号为"+userid+",请记住，以便登录账号开始购物！！！');  \n" +
                        "    window.location.href = 'index.jsp';  \n" +
                        "</script>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
